package inputblog

import (
	"context"
	"fmt"
	"strconv"
	"time"

	"searchcenter/internal/svc"
	"searchcenter/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type PutBlogESLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewPutBlogESLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PutBlogESLogic {
	return &PutBlogESLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *PutBlogESLogic) PutBlogES(req *types.Blog) (resp *types.BaseResponse, err error) {
	// 初始化响应
	resp = &types.BaseResponse{
		Code:    200,
		Message: "success",
	}

	// 验证输入
	if err := validateBlogRequest(req); err != nil {
		resp.Code = 400
		resp.Message = err.Error()
		return resp, nil
	}

	// 转换时间为ISO8601格式（如果需要）
	createTime := req.CreateTime
	if createTime == "" {
		createTime = time.Now().Format("2006-01-02T15:04:05Z07:00")
	}

	// 准备ES文档
	doc := l.prepareBlogDocument(req, createTime)

	// 索引到ES
	if err := l.indexBlogDocument(req.Id, doc); err != nil {
		l.Logger.Errorf("ES indexing error: %v", err)
		resp.Code = 500
		resp.Message = "failed to save blog to search engine"
		return resp, err
	}

	l.Logger.Infof("Blog indexed successfully, ID: %d", req.Id)
	return resp, nil
}

// validateBlogRequest 验证博客请求数据
func validateBlogRequest(req *types.Blog) error {
	if req.Id == 0 {
		return fmt.Errorf("blog id is required")
	}
	if req.Title == "" {
		return fmt.Errorf("blog title is required")
	}
	if len(req.Title) > 200 {
		return fmt.Errorf("title too long, max 200 characters")
	}
	return nil
}

// prepareBlogDocument 准备要索引的文档
func (l *PutBlogESLogic) prepareBlogDocument(req *types.Blog, createTime string) map[string]interface{} {
	return map[string]interface{}{
		"id":         req.Id,
		"AuthorId":   req.UserId,
		"title":      req.Title,
		"content":    req.Content,
		"likeNum":    req.LikeNum,
		"joyNum":     req.JoyNum,
		"joyFeeling": req.JoyFeeling,
		"place":      req.Place,
		"commentNum": req.CommentNum,
		"createTime": createTime,
		"readNum":    req.ReadNum,
		"tags":       req.Tags,
		"timestamp":  time.Now().Unix(), // 添加索引时间戳
		"category":   req.Category,
	}
}

// indexBlogDocument 将博客文档索引到ES
func (l *PutBlogESLogic) indexBlogDocument(id int, doc map[string]interface{}) error {
	return l.svcCtx.ESClient.IndexDocument(
		l.ctx,
		"blog",
		strconv.Itoa(id),
		doc,
	)
}
